<?php
/**
 * Created by b17
 * 3/1/12 5:15 PM
 */

class UserController extends G4T_SecuredController
{
    /**
     * @var \Managers\Users
     */
    private $_userManager;

    /**
     * @var \Managers\Ad
     */
    private $_adManager;

    private $_dateFormat = 'Y-m-d';

    const ADS_PER_PAGE = 10;

    public function init()
    {
        parent::init();
        $this->_userManager = new \Managers\Users();
        $this->_adManager = new \Managers\Ad();
    }

    public function indexAction()
    {
        $user = $this->_userManager->getById($this->_user['id']);
        $this->view->user = $user;

        $page = intval($this->_getParam('page'));

        $adBuilder = new \Managers\Builder\AdBuilder();
        $adBuilder->setUser($this->_user['id']);

        $total = $adBuilder->getTotal();
        $this->view->total = $total;
        $this->displayPaginantor($total, $page, self::ADS_PER_PAGE);

        $offset = $this->_getOffset($page, self::ADS_PER_PAGE);
        $adBuilder->setLimit(self::ADS_PER_PAGE, $offset);
        $ads = $adBuilder->getList();

        $this->view->ads = $ads;
    }

    public function deleteAction()
    {
        $result = $this->_adManager->delete($this->_getParam('id'), $this->_user['id']);
        if ($result) {
            $this->_flashMessenger->addMessage('Объявление успешно удалено.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        } else {
            $this->_flashMessenger->addMessage('Объявление не найдено.', Lib_Flash::ERROR, Lib_Flash::LATER);
        }
        $this->_redirect('/user');
    }

    public function editAction()
    {
        $adBuilder = new \Managers\Builder\AdBuilder();
        $adBuilder->setUser($this->_user['id'])
            ->setId($this->_getParam('id'));
        $ad = $adBuilder->getOne();

        if (!$ad) {
            $this->_redirectNotFound();
        }
        $form = $this->_getAdForm($ad['subCat']['category']['id']);
        $form->populate($ad);
        $this->view->form = $form;

        if ($this->_request->isPost()) {
            if ($form->isValid($this->_getAllParams())) {
                $values = $form->getValues();
                $this->_adManager->update($values);
                $this->_flashMessenger->addMessage('Объявление сохранено.', Lib_Flash::NOTICE, Lib_Flash::LATER);
                $this->_redirect('/user');
            }
        }
    }

    public function promoteAction()
    {
        if ($this->_request->isPost()) {
            $adBuilder = new \Managers\Builder\AdBuilder();
            $adBuilder->setUser($this->_user['id'])
                ->setId($this->_getParam('id'));
            $ad = $adBuilder->getOne();

            if (!$ad) {
                $this->_redirectNotFound();
            }

            try {
                $adManager = new \Managers\Ad();
                $ad = $adManager->promote($ad['id'], $this->_user['id']);
                $this->_flashMessenger->addMessage("Рейтинг успешно повышен до " .
                    $ad->getPromotedDate()->format($this->_dateFormat), Lib_Flash::NOTICE, Lib_Flash::LATER);
                $this->_redirect($this->_getRedirectionUrl());
            } catch (\Managers\Exception\NoMoneyException $e) {
                $this->_flashMessenger->addMessage('У Вас недостаточно денег для повышение рейтинга.', Lib_Flash::ERROR,
                    Lib_Flash::LATER);
                $this->_redirect($this->_getRedirectionUrl());
            }

        } else {
            $this->_redirect($this->_getRedirectionUrl());
        }
    }

    private function _redirectNotFound()
    {
        $this->_flashMessenger->addMessage('Объявление не найдено.', Lib_Flash::ERROR, Lib_Flash::LATER);
        $this->_redirect($this->_getRedirectionUrl());
    }

    private function _getRedirectionUrl()
    {
        $url = $this->getSavedUrl() ? : '/user';
        return $url;
    }

    private function _getAdForm($categoryId)
    {
        $subcatManager = new \Managers\SubCategory();
        $subcats = $subcatManager->getByCategory($categoryId);
        $list = $subcatManager->getSelectList($subcats);

        $formBuilder = \G4T\Form\FormBuilder::createFormBuilder(\Managers\Ad::TABLE)
            ->addField('id', 'hidden')
            ->addField('token', 'hash')
            ->addField('phone', 'string', array('label' => 'Телефон'))
            ->addField('subCat', 'select', array('label' => 'Куда добавить', 'values' => $list))
            ->addField('content', 'text', array('label' => 'Текст объявления', 'rows' => '6', 'style' => 'width:100%'))
            ->addField('submit', 'submit', array('label' => "Добавить", 'class' => 'btn'));

        return $formBuilder->getForm();
    }
}
